define(['jquery', 'bootstrap', 'backend', 'table', 'form'], function ($, undefined, Backend, Table, Form) {

    var Controller = {
        index: () => {
            const { reactive, onMounted } = Vue
            const { ElMessageBox } = ElementPlus
            const index = {
                setup() {
                    const state = reactive({
                        store_id: new URLSearchParams(location.search).get('store_id'),
                        data: [],
                        order: '',
                        sort: '',
                        filter: {
                            drawer: false,
                            data: {
                                status: 'all',
                                createtime: [],
                            },
                            tools: {
                                createtime: {
                                    type: 'tdatetimerange',
                                    label: '创建时间',
                                    value: [],
                                },
                            },
                            condition: {},
                        },
                        statusStyle: {
                            '-1': 'sa-color--danger',
                            0: 'sa-color--info',
                            1: 'sa-color--success',
                        }
                    })

                    const type = reactive({
                        data: {
                            status: [{
                                name: '全部',
                                type: 'all',
                            },
                            {
                                name: '待支付',
                                type: 'unpaid',
                            },
                            {
                                name: '已支付',
                                type: 'paid',
                            },
                            // {
                            //     name: '待发货',
                            //     type: 'nosend',
                            // },
                            {
                                name: '待收货',
                                type: 'noget',
                            },
                            {
                                name: '已完成',
                                type: 'completed',
                            },
                            ],
                        }
                    })

                    function getData() {
                        let tempSearch = JSON.parse(JSON.stringify(state.filter.data));
                        let search = composeFilter(tempSearch, {
                            store_name: 'like',
                            createtime: 'range',
                            updatetime: 'range',
                        });
                        Fast.api.ajax({
                            url: 'sum/store/stock_order',
                            type: 'GET',
                            data: {
                                store_id: state.store_id,
                                page: pagination.page,
                                list_rows: pagination.list_rows,
                                order: state.order,
                                sort: state.sort,
                                ...search,
                            },
                        }, function (ret, res) {
                            state.data = res.data.data
                            pagination.total = res.data.total
                            return false
                        }, function (ret, res) { })
                    }

                    function onChangeSort({ prop, order }) {
                        state.order = order == 'ascending' ? 'asc' : 'desc';
                        state.sort = prop;
                        getData();
                    }
                    function onOpenFilter() {
                        state.filter.drawer = true
                    }
                    function onChangeFilter() {
                        pagination.page = 1
                        getData()
                        state.filter.drawer && (state.filter.drawer = false)
                    }

                    function onChangeTab() {
                        pagination.page = 1
                        getData()
                    }

                    const pagination = reactive({
                        page: 1,
                        list_rows: 10,
                        total: 0,
                    })

                    const batchHandle = reactive({
                        data: [],
                    })
                    function onChangeSelection(val) {
                        batchHandle.data = val
                    }
                    function onBatchHandle(type) {
                        let ids = []
                        batchHandle.data.forEach((item) => {
                            ids.push(item.id)
                        })
                        switch (type) {
                            case 'delete':
                                ElMessageBox.confirm('此操作将删除, 是否继续?', '提示', {
                                    confirmButtonText: '确定',
                                    cancelButtonText: '取消',
                                    type: 'warning',
                                }).then(() => {
                                    onDelete(ids.join(','))
                                });
                                break;
                            default:
                                Fast.api.ajax({
                                    url: `sum/store/stock_order/edit/id/${ids.join(',')}`,
                                    type: 'POST',
                                    data: {
                                        status: type
                                    }
                                }, function (ret, res) {
                                    getData()
                                }, function (ret, res) { })
                                break;
                        }
                    }

                    const handlePopover = reactive({
                        flag: {}
                    })

                    // function onAdd() {
                    //     Fast.api.open("sum/store/store/add?type=add", "添加", {
                    //         callback() {
                    //             getData()
                    //         }
                    //     })
                    // }
                    // function onEdit(id) {
                    //     Fast.api.open(`sum/store/store/edit?type=edit&id=${id}`, "编辑", {
                    //         callback() {
                    //             getData()
                    //         }
                    //     })
                    // }
                    function onPay(id) {
                        Fast.api.open(`sum/store/stock_order/pay?id=${id}`, "支付", {
                            callback() {
                                getData()
                            }
                        })
                    }
                    function onComplete(id) {
                        Fast.api.ajax({
                            url: `sum/store/stock_order/complete/id/${id}`,
                            type: 'Complete',
                        }, function (ret, res) {
                            getData()
                        }, function (ret, res) { })
                    }
                    function onDelete(id) {
                        Fast.api.ajax({
                            url: `sum/store/store/delete/id/${id}`,
                            type: 'DELETE',
                        }, function (ret, res) {
                            getData()
                        }, function (ret, res) { })
                    }
                    // function onRecyclebin() {
                    //     Fast.api.open('sum/store/store/recyclebin', "回收站", {
                    //         callback() {
                    //             getData()
                    //         }
                    //     })
                    // }
                    //
                    // function onGoods(key,title) {
                    //     Fast.api.addtabs(`sum/store/goods/index?store_id=${key}&store_name=${title}`, title+'-商品')
                    // }
                    function statusCode(item) {
                        let data = {
                            class: '',
                            text: item.status_text,
                        }
                        switch (item.status_code) {
                            case 'cancel': // 已取消
                                data.class = 'status-danger';
                                break;
                            case 'closed': // 交易关闭
                                data.class = 'status-danger';
                                break;
                            case 'unpaid': // 待付款
                                data.class = 'status-info';
                                break;
                            case 'nosend': // 待发货
                                data.class = 'status-warning';
                                break;
                            case 'noget': // 待收货
                                data.class = 'status-warning';
                                break;
                            case 'nocomment': // 待评价
                                data.class = 'status-warning';
                                break;
                            case 'commented': // 已评价
                                data.class = 'status-success';
                                break;
                            case 'apply_refund': //申请退款中
                                data.class = 'status-danger';
                                break;
                            case 'refund_completed': // 退款完成
                                data.class = 'status-success';
                                break;
                            case 'refund_agree': // 退款已同意
                                data.class = 'status-success';
                                break;
                            case 'groupon_ing': // 等待成团
                                data.class = 'status-warning';
                                break;
                            case 'groupon_invalid': // 拼团失败
                                data.class = 'status-danger';
                                break;
                            case 'completed': // 交易完成
                                data.class = 'status-success';
                                break;
                        }
                        return data
                    }
                    onMounted(() => {
                        getData()
                    })

                    return {
                        onClipboard,
                        state,
                        type,
                        getData,
                        onChangeSort,
                        onOpenFilter,
                        onChangeFilter,
                        onChangeTab,
                        pagination,
                        handlePopover,
                        batchHandle,
                        onChangeSelection,
                        onBatchHandle,
                        // onAdd,
                        // onEdit,
                        onDelete,
                        // onRecyclebin,
                        // onGoods,
                        statusCode,
                        onPay,
                        onComplete,
                    }
                }
            }
            createApp('index', index);
        },
        add: () => {
            Controller.form();
        },
        edit: () => {
            Controller.form();
        },
        form: () => {
            const { reactive, onMounted, getCurrentInstance,computed } = Vue
            const addEdit = {
                setup() {
                    const { proxy } = getCurrentInstance();

                    const state = reactive({
                        type: new URLSearchParams(location.search).get('type'),
                        id: new URLSearchParams(location.search).get('id'),
                        store_id: new URLSearchParams(location.search).get('store_id'),
                        goods_id: new URLSearchParams(location.search).get('goods_id'),
                    })

                    const form = reactive({
                        model: {
                            goods:{
                                image:'',
                                stock_price:0
                            },
                            type: 'normal', // 订单类型
                            goods_num:0,
                            consignee:'',
                            mobile:'',
                            province_name: '',
                            province_id: '',
                            city_name: '',
                            city_id: '',
                            district_name: '',
                            district_id: '',
                            address:'',
                            pcd:[],
                        },
                        rules: {
                            goods_num: [{ required: true, message: '请输入进货数量', trigger: 'blur' }],
                            consignee: [{ required: true, message: '请输入收货人', trigger: 'blur' }],
                            mobile: [{ required: true, message: '请输入收货人联系电话', trigger: 'blur' }],
                            pcd: [{ required: true, message: '请选择省市区', trigger: 'blur' }],
                            address: [{ required: true, message: '请输入地址详情', trigger: 'blur' }],
                        },
                    })
                    const order_amount = computed(() => {
                      return form.model.goods.stock_price*form.model.goods_num
                    })

                    // 进货价按商户设置
                    // function getGoodsDetail() {
                    //     Fast.api.ajax({
                    //         url: `sum/goods/goods/detail/id/${state.goods_id}`,
                    //         type: 'GET',
                    //     }, function (ret, res) {
                    //         form.model.goods = res.data;
                    //         return false
                    //     }, function (ret, res) { })
                    // }
                    function getStoreGoodsDetail() {
                        Fast.api.ajax({
                            url: `sum/store/goods/detail?goods_id=${state.goods_id}&store_id=${state.store_id}`,
                            type: 'GET',
                        }, function (ret, res) {
                            form.model.goods = res.data.goods;
                            form.model.goods.stock_price = res.data.stock_price;
                            return false
                        }, function (ret, res) { })
                    }

                    function onConfirm() {
                        proxy.$refs['formRef'].validate((valid) => {
                            if (valid) {
                                let label = proxy.$refs['addressRef'].getCheckedNodes()[0].pathLabels;
                                let tempForm = JSON.parse(JSON.stringify(form.model));
                                tempForm = {
                                    ...tempForm,
                                    store_id:state.store_id,
                                    goods_id:state.goods_id,
                                    province_name: label[0],
                                    province_id: form.model.pcd[0],
                                    city_name: label[1],
                                    city_id: form.model.pcd[1],
                                    district_name: label[2],
                                    district_id: form.model.pcd[2],
                                };
                                delete tempForm.goods;
                                delete tempForm.pcd;
                                Fast.api.ajax({
                                    url: state.type == 'add' ? 'sum/store/stock_order/add' : `sum/store/stock_order/edit/id/${state.id}`,
                                    type: 'POST',
                                    data: tempForm,
                                }, function (ret, res) {
                                    Fast.api.open(`sum/store/stock_order/pay?id=${res.data.id}`, "进货支付", {
                                        callback: function () {
                                            Fast.api.close()
                                        }
                                    });
                                    return false
                                    // Fast.api.close()
                                }, function (ret, res) { })
                            }
                        });
                    }

                    const area = reactive({
                        select: []
                    })
                    function getAreaSelect() {
                        Fast.api.ajax({
                            url: 'sum/data/area/select',
                            type: 'GET',
                        }, function (ret, res) {
                            area.select = res.data;
                            return false
                        }, function (ret, res) { })
                    }

                    function onChangeOrderType(type) {
                        form.model.type = type;
                    }

                    onMounted(() => {
                        // getGoodsDetail()
                        getStoreGoodsDetail()
                        getAreaSelect()
                        // state.type == 'edit' && getDetail()
                    })

                    return {
                        state,
                        form,
                        onConfirm,
                        onChangeOrderType,
                        area,
                        getAreaSelect,
                        order_amount,
                    }
                }
            }
            createApp('addEdit', addEdit);
        }
    };
    return Controller;
});
